<?php
/*
alert提示
在预定义字符前加上反斜杠，包括 单引号、双引号、反斜杠、NULL，以保护数据库安全
生成随机字符串，包含大写、小写字母、数字
转换时间戳为常用的日期格式
获取IP
计算时间差：默认返回类型为“分钟”
获取当前页面的URL地址
跳转函数
获得本周起始时间
获得本月起始时间
模拟GET请求
模拟POST请求
发送HTTP状态
彩色导出
*/


//alert提示
function alert($msg){
	echo "<script>alert('$msg');</script>";
}
//把一些预定义的字符转换为 HTML 实体
function d_htmlspecialchars($string) {
	if(is_array($string)) {
		foreach($string as $key => $val) {
			$string[$key] = d_htmlspecialchars($val);
		}
	} else {
		$string = str_replace('&', '&', $string);
		$string = str_replace('"', '"', $string);
		$string = str_replace(''', ''', $string);
		$string = str_replace('<', '<', $string);
		$string = str_replace('>', '>', $string);
		$string = preg_replace('/&(#\d;)/', '&\1', $string);
	}
	return $string;
}
//在预定义字符前加上反斜杠，包括 单引号、双引号、反斜杠、NULL，以保护数据库安全
function d_addslashes($string, $force = 0) {
		if(!$GLOBALS['magic_quotes_gpc'] || $force) {
		if(is_array($string)) {
			foreach($string as $key => $val) $string[$key] = d_addslashes($val, $force);
		}else{
			$string = addslashes($string);
		}
	}
	return $string;
}
//生成随机字符串，包含大写、小写字母、数字
function randstr($length) {
	$hash = '';
	$chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz';
	$max = strlen($chars) - 1;
	mt_srand((double)microtime() * 1000000);
	for($i = 0; $i < $length; $i++) {
		$hash .= $chars[mt_rand(0, $max)];
	}
	return $hash;
}
//转换时间戳为常用的日期格式
function trans_time($timestamp){
	if($timestamp < 1)
		echo '无效的Unix时间戳';
	else
		return date("Y-m-d H:i:s",$timestamp);
}
//获取IP
function get_ip() {
	if ($_SERVER["HTTP_X_FORWARDED_FOR"])
		$ip = $_SERVER["HTTP_X_FORWARDED_FOR"];
	else if ($_SERVER["HTTP_CLIENT_IP"])
		$ip = $_SERVER["HTTP_CLIENT_IP"];
	else if ($_SERVER["REMOTE_ADDR"])
		$ip = $_SERVER["REMOTE_ADDR"];
	else if (getenv("HTTP_X_FORWARDED_FOR"))
		$ip = getenv("HTTP_X_FORWARDED_FOR");
	else if (getenv("HTTP_CLIENT_IP"))
		$ip = getenv("HTTP_CLIENT_IP");
	else if (getenv("REMOTE_ADDR"))
		$ip = getenv("REMOTE_ADDR");
	else
		$ip = "Unknown";
	return $ip;
}
//计算时间差：默认返回类型为“分钟”
//$old_time 只能是时间戳，$return_type 为 h 是小时，为 s 是秒
function timelag($old_time,$return_type='m'){
	if($old_time < 1){
		echo '无效的Unix时间戳';
	} else {
		switch($return_type){
			case 'h':
				$type = 3600; break;
			case 'm':
				$type = 60; break;
			case 's':
				$type = 1; break;
			case '':
				$type = 60; break;
		}
		$dif = round( (time()-$old_time)/$type ) ;
		return $dif;
	}
}
//获取当前页面的URL地址
function url_this(){
	$url = "http://".$_SERVER ["HTTP_HOST"].$_SERVER["REQUEST_URI"];
	$return_url = "< a href=' '>$url</ a>";
	return $return_url;
}
//跳转函数
function url_redirect($url,$delay=''){
	if($delay == ''){
		echo "<script>window.location.href='$url'</script>";
	}else{
		echo "<meta http-equiv='refresh' content='$delay;URL=$url' />";
	}
}


/**
 * 获得本周起始时间
 *
 * @Author hujun <hujun@migoedu.com>
 * @param $date
 * @param bool $sec
 * @return bool
 */
function getWeek($date, $his = false) {
    $time = strtotime($date);
    if ($time) {
        if ($his) {
            $data['0'] = date('Y-m-d H:i:s',($time-((date('w', $time)==0?7:date('w', $time))-1)*24*3600));
            $data['1'] = date('Y-m-d H:i:s',($time+(7-(date('w', $time)==0?7:date('w', $time)))*24*3600));
        } else {
            $data['0'] = date('Y-m-d',($time-((date('w', $time)==0?7:date('w', $time))-1)*24*3600));
            $data['1'] = date('Y-m-d',($time+(7-(date('w', $time)==0?7:date('w', $time)))*24*3600));
        }
    } else {
        $data = false;
    }
    return $data;
}

/**
 * 获得本月起始时间
 *
 * @Author hujun <hujun@migoedu.com>
 * @param $date
 * @param bool $his
 * @return bool
 */
function getMonth($date, $his = false) {
    $time = strtotime($date);
    if ($time) {
        if ($his) {
            $data['0'] = date('Y-m-01 H:i:s', $time);
            $data['1'] = date('Y-m-d  H:i:s', strtotime($data['0']." +1 month -1 day"));
        } else {
            $data['0'] = date('Y-m-01', $time);
            $data['1'] = date('Y-m-d', strtotime($data['0']." +1 month -1 day"));
        }
    } else {
        $data = false;
    }

    return $data;
}

/**
 * 模拟GET请求
 *
 * @param string $url
 * @param string $data_type
 *
 * @return mixed
 *
 * Examples:
 * ```
 * HttpCurl::get('http://api.example.com/?a=123&b=456', 'json');
 * ```
 */
function get($url, $data_type='text')
{
    $cl = curl_init();
    if(stripos($url, 'https://') !== FALSE) {
        curl_setopt($cl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($cl, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($cl, CURLOPT_SSLVERSION, 1);
    }
    curl_setopt($cl, CURLOPT_URL, $url);
    curl_setopt($cl, CURLOPT_RETURNTRANSFER, 1 );
    $content = curl_exec($cl);
    $status = curl_getinfo($cl);
    curl_close($cl);
    if (isset($status['http_code']) && $status['http_code'] == 200) {
        if ($data_type == 'json') {
            $content = json_decode($content);
        }
        return $content;
    } else {
        return FALSE;
    }
}

/**
 * 模拟POST请求
 *
 * @param string $url
 * @param array $fields
 * @param string $data_type
 *
 * @return mixed
 *
 * Examples:
 * ```
 * HttpCurl::post('http://api.example.com/?a=123', array('abc'=>'123', 'efg'=>'567'), 'json');
 * HttpCurl::post('http://api.example.com/', '这是post原始内容', 'json');
 * 文件post上传
 * HttpCurl::post('http://api.example.com/', array('abc'=>'123', 'file1'=>'@/data/1.jpg'), 'json');
 * ```
 */
function post($url, $fields, $data_type='text')
{
    $cl = curl_init();
    if(stripos($url, 'https://') !== FALSE) {
        curl_setopt($cl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($cl, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($cl, CURLOPT_SSLVERSION, 1);
    }
    curl_setopt($cl, CURLOPT_URL, $url);
    curl_setopt($cl, CURLOPT_RETURNTRANSFER, 1 );
    curl_setopt($cl, CURLOPT_POST, true);
    curl_setopt($cl, CURLOPT_POSTFIELDS, $fields);
    $content = curl_exec($cl);
    $status = curl_getinfo($cl);
    curl_close($cl);
    if (isset($status['http_code']) && $status['http_code'] == 200) {
        if ($data_type == 'json') {
            $content = json_decode($content);
        }
        return $content;
    } else {
        return FALSE;
    }
}

/**
 * 发送HTTP状态
 * @param integer $code 状态码
 * @return void
 */
function send_http_status($code) {
    static $_status = array(
        // Informational 1xx
        100 => 'Continue',
        101 => 'Switching Protocols',
        // Success 2xx
        200 => 'OK',
        201 => 'Created',
        202 => 'Accepted',
        203 => 'Non-Authoritative Information',
        204 => 'No Content',
        205 => 'Reset Content',
        206 => 'Partial Content',
        // Redirection 3xx
        300 => 'Multiple Choices',
        301 => 'Moved Permanently',
        302 => 'Moved Temporarily ', // 1.1
        303 => 'See Other',
        304 => 'Not Modified',
        305 => 'Use Proxy',
        // 306 is deprecated but reserved
        307 => 'Temporary Redirect',
        // Client Error 4xx
        400 => 'Bad Request',
        401 => 'Unauthorized',
        402 => 'Payment Required',
        403 => 'Forbidden',
        404 => 'Not Found',
        405 => 'Method Not Allowed',
        406 => 'Not Acceptable',
        407 => 'Proxy Authentication Required',
        408 => 'Request Timeout',
        409 => 'Conflict',
        410 => 'Gone',
        411 => 'Length Required',
        412 => 'Precondition Failed',
        413 => 'Request Entity Too Large',
        414 => 'Request-URI Too Long',
        415 => 'Unsupported Media Type',
        416 => 'Requested Range Not Satisfiable',
        417 => 'Expectation Failed',
        // Server Error 5xx
        500 => 'Internal Server Error',
        501 => 'Not Implemented',
        502 => 'Bad Gateway',
        503 => 'Service Unavailable',
        504 => 'Gateway Timeout',
        505 => 'HTTP Version Not Supported',
        509 => 'Bandwidth Limit Exceeded'
    );
    if(isset($_status[$code])) {
        header('HTTP/1.1 '.$code.' '.$_status[$code]);
        // 确保FastCGI模式下正常
        header('Status:'.$code.' '.$_status[$code]);
    }
}


/**
 * 彩色导出
 * @param $fileName
 * @param $headArr
 * @param $data
 */
function getExcel($fileName,$headArr,$data) {
    $str = "<table border=\"1\">";
    $str .= "<tr style=\"font-weight:bold;\">";
    foreach ($headArr as $k=> $v){
        $str .= "<td style=\"background:#498CD0;text-align: center\">" . $v . "</td>";
    }
    $str .= "</tr>";
    if (!empty($data)) {
        foreach($data as $key=>$item){
            $str .= "<tr>";
            foreach ($item as $v) {
                $str .= "<td>" . $v . "</td>";
            }
            $str .= "</tr>";
        }
    }
    $str .= "</table>";
    $sheetName =  $fileName.".xls";
    $sheetName = iconv("UTF-8","UTF-8",$sheetName);
    header('Content-Length: ' . strlen($str));
    header("Content-type:application/vnd.ms-excel");
    header("Content-Disposition:filename=".$sheetName);
    echo $str;
    exit();
}


function workDays($year, $month)
{
    $day = 1;
    $days = 0;
    $t = mktime(0, 0, 0, $month, $day, $year);
    $days = date('t', $t);
    $fristDayWeek = date('w', $t);//每月一号的星期数
    $lastDayWeek = date('w', mktime(0, 0, 0, $month, $days, $year));//每月最后一天的星期数
    if ($days > 28) {//非平年二月算法，平年二月无论怎么都只有20天。
        if ($fristDayWeek == 6)//起始日是星期六的减去2天，星期天的减去一天。
            $days -= 2;
        if ($fristDayWeek == 0)
            $days -= 1;
        if ($lastDayWeek == 6)//结束日是星期六的减去一天，星期天的减去2天。
            $days -= 1;
        if ($lastDayWeek == 0)
            $days -= 2;
    }

    if ($days < 28)//每个月最少会工作20天，此处修正开始日期是星期六，结束日期是星期天的31天的月份

        $days = 28;
    return $days - 8;// 减去每个月都有的4个星期天共8天
}

echo workDays(2020, 7);







?>